/**
 * @Description: dom相关操作
 * @Autor: Yao
 * @Date: 2020-03-26 09:52:48
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-03-26 09:53:04
 * @module dom
 */

/**
 * @description 获取窗口可视范围的高度
 * @returns {Number} 高度（类型number）
 */
export function getClientHeight() {
  let clientHeight = 0
  if (document.body.clientHeight && document.documentElement.clientHeight) {
    clientHeight =
      document.body.clientHeight < document.documentElement.clientHeight
        ? document.body.clientHeight
        : document.documentElement.clientHeight
  } else {
    clientHeight =
      document.body.clientHeight > document.documentElement.clientHeight
        ? document.body.clientHeight
        : document.documentElement.clientHeight
  }
  return clientHeight
}

/**
 * @description 获取窗口可视范围宽度
 * @returns {Number} 宽度（类型number）
 */
export function getClientWidth() {
  let d = document,
    a = d.compatMode === 'BackCompat' ? d.body : d.documentElement
  return a.clientWidth
}

/**
 * @description 获取窗口尺寸 retuen->object(w宽度，h高度)
 * @returns {Object}
 */
export function getViewportOffset() {
  if (window.innerWidth) {
    return {
      w: window.innerWidth,
      h: window.innerHeight,
    }
  } else {
    // ie8及其以下
    if (document.compatMode === 'BackCompat') {
      // 怪异模式
      return {
        w: document.body.clientWidth,
        h: document.body.clientHeight,
      }
    } else {
      // 标准模式
      return {
        w: document.documentElement.clientWidth,
        h: document.documentElement.clientHeight,
      }
    }
  }
}

/**
 * @description 开启全屏
 * @param {Element} element dom节点
 */
export function launchFullscreen(element = document.body) {
  if (element.requestFullscreen) {
    element.requestFullscreen()
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen()
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen()
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullScreen()
  }
}

/**
 * @description 退出全屏
 */
export function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen()
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen()
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen()
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen()
  }
}

/**
 * @description 滚动到指定元素区域
 * @param {Element} element dom节点
 */
export function smoothScroll(element) {
  document.querySelector(element).scrollIntoView({
    behavior: 'smooth',
  })
}

/**
 * @description 平滑滚动到页面顶部（只适用于正常文档下的滚动条，某个div之类的dom元素的滚动条无效）
 */
export function scrollToTop() {
  const c = document.documentElement.scrollTop || document.body.scrollTop
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop)
    window.scrollTo(0, c - c / 8)
  }
}
